Обробка помилок та винятків (Exception Handling)

У Spring Boot обробка винятків дозволяє правильно керувати помилками та надавати користувачам коректні відповіді. Використовується механізм **@ExceptionHandler** та глобальна обробка через **@ControllerAdvice**.

1. Локальна обробка винятків (@ExceptionHandler)

@ExceptionHandler використовується у контролерах для обробки певних типів винятків.

                
                @RestController
                @RequestMapping("/users")
                public class UserController {
                    @GetMapping("/{id}")
                    public User getUser(@PathVariable Long id) {
                        return userService.findById(id)
                            .orElseThrow(() -> new UserNotFoundException("User not found"));
                    }
                    
                    @ExceptionHandler(UserNotFoundException.class)
                    public ResponseEntity handleUserNotFound(UserNotFoundException ex) {
                        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
                    }
                }
                
            

2. Глобальна обробка помилок (@ControllerAdvice)

@ControllerAdvice використовується для централізованого оброблення винятків по всьому додатку.

                
                @ControllerAdvice
                public class GlobalExceptionHandler {
                    
                    @ExceptionHandler(UserNotFoundException.class)
                    public ResponseEntity handleUserNotFound(UserNotFoundException ex) {
                        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
                    }
                    
                    @ExceptionHandler(Exception.class)
                    public ResponseEntity handleGenericException(Exception ex) {
                        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                            .body("Unexpected error occurred: " + ex.getMessage());
                    }
                }
                
            

3. Створення власного винятку

                
                public class UserNotFoundException extends RuntimeException {
                    public UserNotFoundException(String message) {
                        super(message);
                    }
                }
                
            

4. Використання ResponseEntity для контролю статусів

                
                @RestController
                @RequestMapping("/users")
                public class UserController {
                    @GetMapping("/{id}")
                    public ResponseEntity getUser(@PathVariable Long id) {
                        return userService.findById(id)
                            .map(user -> ResponseEntity.ok(user))
                            .orElse(ResponseEntity.status(HttpStatus.NOT_FOUND).build());
                    }
                }
                
            

Назад Далі